package com.eight.cloud.mybatisplus.handler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.eight.cloud.core.global.model.BaseUser;
import com.eight.cloud.mybatisplus.config.SaasConfig;
import com.eight.cloud.core.utils.supply.UserContext;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;

import java.util.List;
import java.util.Objects;

/**
 * 多租户处理器
 *
 * @ClassName: MpTenantHandler
 * @Author: TXC
 * @Date: 2024-10-28 16:39
 **/
@Slf4j
public class MpTenantHandler implements TenantLineHandler {
    private final SaasConfig saaSConfig;

    public MpTenantHandler(SaasConfig saaSConfig) {
        this.saaSConfig = saaSConfig;
    }

    @Override
    public Expression getTenantId() {
        BaseUser baseUser = UserContext.getUser();
        if (Objects.isNull(baseUser)) {
            return null;
        }
        String tenantId = baseUser.getTenantId();
        return new StringValue(tenantId);
    }

    @Override
    public String getTenantIdColumn() {
        return saaSConfig.getTenantId();
    }

    @Override
    public boolean ignoreTable(String tableName) {
        // 超级管理员端的表可以进行忽略(如 租户管理表等)
        List<String> ignoreTables = saaSConfig.getIgnoreTables();
        long count = ignoreTables.stream().filter(e -> e.equalsIgnoreCase(tableName)).count();
        BaseUser user = UserContext.getUser();
        return count > 0 || ObjectUtil.isNull(user) || StrUtil.isBlank(user.getTenantId());
    }
}
